package org.apereo.cas.web.flow.config;

import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.web.flow.CasKaptchaWebflowConfigurer;
import org.apereo.cas.web.flow.CasWebflowConfigurer;
import org.apereo.cas.web.flow.CasWebflowExecutionPlan;
import org.apereo.cas.web.flow.CasWebflowExecutionPlanConfigurer;
import org.apereo.cas.web.flow.ValidateKaptchaAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.webflow.definition.registry.FlowDefinitionRegistry;
import org.springframework.webflow.engine.builder.support.FlowBuilderServices;
import org.springframework.webflow.execution.Action;

import lombok.extern.slf4j.Slf4j;

/**
 * 参照 cas-server-support-captcha模块做修改
 * 
 * @description
 * @author linzl
 * @email 2225010489@qq.com
 * @date 2018年7月25日
 */
@Configuration("casKaptchaConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
@ConditionalOnProperty(prefix = "cas.custom.properties.kaptcha", name = "enabled", havingValue = "true", matchIfMissing = true)
@Slf4j
public class CasKaptchaConfiguration implements CasWebflowExecutionPlanConfigurer {

	@Autowired
	@Qualifier("loginFlowRegistry")
	private FlowDefinitionRegistry loginFlowDefinitionRegistry;

	@Autowired
	private FlowBuilderServices flowBuilderServices;

	@Autowired
	private ApplicationContext applicationContext;

	@Autowired
	private CasConfigurationProperties casProperties;

	@ConditionalOnMissingBean(name = "kaptchaWebflowConfigurer")
	@Bean
	@DependsOn("defaultWebflowConfigurer")
	public CasWebflowConfigurer kaptchaWebflowConfigurer() {
		return new CasKaptchaWebflowConfigurer(flowBuilderServices, loginFlowDefinitionRegistry, applicationContext,
				casProperties);
	}

	@RefreshScope
	@Bean
	public Action validateKaptchaAction() {
		return new ValidateKaptchaAction(casProperties.getCustom());
	}

	@Override
	public void configureWebflowExecutionPlan(final CasWebflowExecutionPlan plan) {
		log.error("CasKaptchaConfiguration");
		plan.registerWebflowConfigurer(kaptchaWebflowConfigurer());
	}
}
